package com.qf.drbackend.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qf.drbackend.pojos.R;
import com.qf.drbackend.pojos.ShoppingCart;
import com.qf.drbackend.server.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @GetMapping("/list")
    public R list(){
        //获取当前登录用户的id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String uidStr = (String) authentication.getPrincipal();

        Long uid = Long.parseLong(uidStr);

        //获取当前登录用户的购物车数据
        Wrapper<ShoppingCart> qw = Wrappers.lambdaQuery(ShoppingCart.class).eq(ShoppingCart::getUserId,uid);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(qw);

        return R.success(shoppingCarts);
    }

    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart){

        String uid = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        shoppingCart.setUserId(Long.parseLong(uid));
        shoppingCart.setNumber(1);

        ShoppingCart one = shoppingCartService.getOne(Wrappers.lambdaQuery(ShoppingCart.class).eq(ShoppingCart::getDishId, shoppingCart.getDishId()));
        if (one != null){
            //如果之前添加过，更新数量
            one.setNumber(one.getNumber()+1);
            shoppingCartService.updateById(one);

            return R.success(one);
        }else {
            //之前没有添加过，新增
            shoppingCartService.save(shoppingCart);

            return R.success(shoppingCart);
        }
    }
}
